import React, { useEffect, useState } from 'react';
import { Row } from 'antd';
import { RowProps } from './../../components/row/Row';
import styles from './../../components/row/row.module.scss';
import classNames from 'classnames';

export const printOnEveryPageClassName = 'row-print-on-every-page';

const ControlMap = {
  'table': (props: any) => (
    <table
      border={0}
      cellSpacing={0}
      cellPadding={2}
      {...props}
      className={styles.table} />
  ),
  'table-header-group': (props: any) => <thead {...props} />,
  'table-row-group': (props: any) => <tbody {...props} className='' />,
  'table-row': (props: any) => <tr {...props} className='' />
};

export default (props: RowProps) => {
  const { rowProps } = props;
  const [height, setHeight] = useState<null | string>(null);
  const [top, setTop] = useState<null | string>(null);

  useEffect(() => {
    if (props.id) {
      const tr = document.querySelector('#' + props.id!);

      if (tr) {
        const parentNode: any = tr.parentNode;

        if (parentNode && parentNode.tagName.toUpperCase() === 'TD') {
          const parentchildren = Number(parentNode.dataset.parentchildren);
          const trChild = parentNode.querySelectorAll(`tr`);

          if (trChild.length) {
            let curIndex = 0;

            trChild.forEach((item: any, index: number) => {
              if (item.id === props.id) {
                curIndex = index;
              }
            });

            setTop(100 / parentchildren * curIndex + '%');
          }

          if (parentchildren) {
            setHeight(100 / parentchildren + '%');
          }
        }
      }
    }
  }, [props.id]);

  let Component: any = Row;

  const style: React.CSSProperties = {
    'pageBreakBefore': "auto",
    'breakInside': "avoid",
  };

  if (rowProps?.tableStyle) {
    Component = ControlMap[rowProps.tableStyle];

    if (rowProps.pageBreakAfter === false) {
      style.pageBreakAfter = 'auto';
    }
  }

  if (height) style.height = height;
  if (top) style.top = top;

  return (
    <Component
      {...props}
      {...rowProps}
      className={classNames(styles.row, {
        [printOnEveryPageClassName]: rowProps?.printOnEveryPage
      })}
      style={style} />
  );
};